using UnityEngine;
using UnityEngine.AI;

public class NPCMovement : MonoBehaviour
{
    private NavMeshAgent navMeshAgent;

    public float wanderRadius = 10f;
    public float wanderTimer = 5f;

    private float timer;

    void Start()
    {
        navMeshAgent = GetComponent<NavMeshAgent>();
        timer = wanderTimer;

        // Start wandering when the script begins
        Wander();
    }

    void Update()
    {
        // If the NPC has reached its destination or the timer has expired, wander again
        if (!navMeshAgent.pathPending && navMeshAgent.remainingDistance < 0.5f)
        {
            timer -= Time.deltaTime;
            if (timer <= 0f)
            {
                Wander();
                timer = wanderTimer;
            }
        }
    }

    void Wander()
    {
        // Generate a random point within the wander radius
        Vector3 randomPoint = Random.insideUnitSphere * wanderRadius;
        randomPoint += transform.position;

        // Ensure the point is on the NavMesh
        NavMeshHit hit;
        NavMesh.SamplePosition(randomPoint, out hit, wanderRadius, NavMesh.AllAreas);

        // Set the destination to the random point
        navMeshAgent.SetDestination(hit.position);
    }
}